#include <Windows.h>
#include <WindowsX.h>
#include <tchar.h>
#include "resource.h"

struct SThreadInfo
{
	UINT	nMax;
	HWND	hListBox;
};

DWORD CALLBACK ThreadProc(LPVOID lpData)
{
	SThreadInfo* pThreadInfo = (SThreadInfo*)lpData;

	DWORD dwStart = GetTickCount();
	TCHAR szTmp[MAX_PATH];
	for (int ii = 0; ii < pThreadInfo->nMax; ii++)
	{
		_stprintf(szTmp, _T("0x%06X print %d "), GetCurrentThreadId(), ii + 1);
		ListBox_AddString(pThreadInfo->hListBox, szTmp);
		SendMessage(pThreadInfo->hListBox, WM_VSCROLL, SB_BOTTOM, 0);
	}
	delete pThreadInfo;
	
	_stprintf(szTmp, _T("Time:  %d"), GetTickCount() - dwStart);
	OutputDebugString(szTmp);

	return 0;
}

int CALLBACK DlgProc(HWND hDlg, UINT nMsg, WPARAM wParam, LPARAM lParam)
{
	static HANDLE hThreads[2];

	switch (nMsg)
	{
		case WM_INITDIALOG:
		{
			SetWindowText(hDlg, _T("Demo0094"));

			UINT nWidth		= GetSystemMetrics(SM_CXSCREEN);
			UINT nHeight	= GetSystemMetrics(SM_CYSCREEN);
			RECT rtClient;
			GetClientRect(hDlg, &rtClient);
			SetWindowPos(hDlg, NULL, (nWidth - (rtClient.right - rtClient.left)) / 2, (nHeight - (rtClient.bottom - rtClient.top)) / 2, 0, 0, SWP_NOSIZE);
			
			break;
		}
		case WM_COMMAND:
		{
			switch (LOWORD(wParam))
			{
				case IDC_BTNSTART:
				{	
					SThreadInfo* pThreadInfo1	= new SThreadInfo;
					SThreadInfo* pThreadInfo2	= new SThreadInfo;
					pThreadInfo1->nMax			= 5000;
					pThreadInfo1->hListBox		= GetDlgItem(hDlg, IDC_LIST1);
					pThreadInfo2->nMax			= 5000;
					pThreadInfo2->hListBox		= GetDlgItem(hDlg, IDC_LIST2);
					hThreads[0] = CreateThread(NULL, 0, ThreadProc, (LPVOID)pThreadInfo1, CREATE_SUSPENDED, 0);
					hThreads[1] = CreateThread(NULL, 0, ThreadProc, (LPVOID)pThreadInfo2, CREATE_SUSPENDED, 0);
					SetThreadPriority(hThreads[0], THREAD_PRIORITY_HIGHEST);
					SetThreadPriority(hThreads[1], THREAD_PRIORITY_LOWEST);
					ResumeThread(hThreads[0]);
					ResumeThread(hThreads[1]);

					break;
				}
				case IDC_BTNEXIT:
				{
					DWORD dwExitCode1;
					DWORD dwExitCode2;
					GetExitCodeThread(hThreads[0], &dwExitCode1);
					if (dwExitCode1 == STILL_ACTIVE)
					{
						TerminateThread(hThreads[0], dwExitCode1);
					}
					
					GetExitCodeThread(hThreads[1], &dwExitCode2);			
					if (dwExitCode2 == STILL_ACTIVE)
					{
						TerminateThread(hThreads[1], dwExitCode2);
					}
					Sleep(200);
					WaitForMultipleObjects(2, hThreads, TRUE, INFINITE);
					CloseHandle(hThreads[0]);
					CloseHandle(hThreads[1]);
					PostQuitMessage(0);

					break;
				}
			}

			break;
		}
		case WM_CLOSE:
		{
			PostQuitMessage(0);
			break;
		}
	}

	return 0;
}

BOOL WINAPI _tWinMain(HINSTANCE hInstance, HINSTANCE hPreInstance, LPTSTR szCmdLine, int nShowCmd)
{
	DialogBox(hInstance, MAKEINTRESOURCE(IDD_DIALOG), NULL, DlgProc);

	return TRUE;
}